<?php

namespace app\scm\controller;

use app\admin\common\Base;
use think\Db;
use app\scm\model\Invpu as Model;

class Invpusummarysupplier extends Base
{
    public function index()
    {
        $data = $this->request->param();

        if (isset($data['ajax']) && $data['ajax'] == 100) {
            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);

            if (isset($data['startdate']) && isset($data['enddate'])) {
                // 采购
                $sql = Db::name('order_good')->alias('a')->join('order b', 'a.order_id = b.id')->where('b.addtime', '>=', strtotime($data['startdate']))->where('b.addtime', '<=', strtotime($data['enddate']))->where('o_type', 4)->where(['b.is_del' => 0, 'b.enterprise_id' => $this->EnterpriseId]);
                $sql = $data['supplierid'] == '' ? $sql : $sql->where('b.user_id', $data['supplierid']);
                $sql = $data['goodsid'] == '' ? $sql : $sql->where('a.good_id', $data['goodsid']);
                $sql = $data['storeid'] == '' ? $sql : $sql->where('a.store_id', $data['storeid']);
                $sql = $sql->field('a.*,b.*,sum(a.shuliang) as number, sum(b.payment) as payment, sum(a.price) as price, sum(a.total_price) as purchase_price, sum(a.tax_e) as tax_price, sum(a.total_price) as sum_price_tax');
                $sql = $sql->group('a.good_id, a.store_id');
                // 供应商类别
                if (!isset($data['supplier_category_id']) || $data['supplier_category_id'] == 0 || $data['supplier_category_id'] == '') {
                } else {
                    $c = Db::name('customer')->where('category_id', $data['supplier_category_id'])->select();
                    $c['ids'] = implode(',', array_column($c, 'id'));
                    $sql->where('b.user_id', 'in', $c['ids']); //商品类别
                }
                $list = $sql->select();
                $count = $sql->count();

                // 退货
                $qsql = Db::name('order_good')->alias('a')->join('order b', 'a.order_id = b.id')->where('b.addtime', '>=', strtotime($data['startdate']))->where('b.addtime', '<=', strtotime($data['enddate']))->where('o_type', 4)->where(['b.is_del' => 0, 'b.enterprise_id' => $this->EnterpriseId]);
                $qsql = $data['supplierid'] == '' ? $qsql : $qsql->where('b.user_id', $data['supplierid']);
                $qsql = $data['goodsid'] == '' ? $qsql : $qsql->where('a.good_id', $data['goodsid']);
                $qsql = $data['storeid'] == '' ? $qsql : $qsql->where('a.store_id', $data['storeid']);
                $qsql = $qsql->field('a.*,b.*,sum(a.shuliang) as number, sum(b.payment) as payment, sum(a.price) as price, sum(a.total_price) as purchase_price, sum(a.tax_e) as tax_price, sum(a.total_price) as sum_price_tax');
                $qsql = $qsql->group('a.good_id, a.store_id');
                // 供应商类别
                if (!isset($data['supplier_category_id']) || $data['supplier_category_id'] == 0 || $data['supplier_category_id'] == '') {
                } else {
                    $d = Db::name('customer')->where('category_id', $data['supplier_category_id'])->select();
                    $d['ids'] = implode(',', array_column($d, 'id'));
                    $qsql->where('b.user_id', 'in', $d['ids']); //商品类别
                }
                $qlist = $qsql->select();

                // 减去退货
                foreach ($list as $key => $value) {
                    foreach ($qlist as $k => $v) {
                        if ($v['good_id'] == $value['good_id'] && $v['store_id'] == $value['store_id']) {
                            $list[$key]['number'] = round($value['number'] - $v['number'], 2);
                            $list[$key]['price'] = round($value['price'] - $v['price'], 2);
                            $list[$key]['payment'] = round($value['payment'] - $v['payment'], 2);
                            $list[$key]['purchase_price'] = round($value['purchase_price'] - $v['purchase_price'], 2);
                            $list[$key]['tax_price'] = round($value['tax_price'] - $v['tax_price'], 2);
                            $list[$key]['sum_price_tax'] = round($value['sum_price_tax'] - $v['sum_price_tax'], 2);
                        }
                    }
                }

                foreach ($list as $key => $value) {
                    $customer = Db::name('customer')->where('id', $value['user_id'])->find();
                    $list[$key]['supplier_category'] = Db::name('customer_category')->where('id', $customer['category_id'])->value('name');
                    $list[$key]['supplier_name'] = $customer['name'];
                    $goods = Db::name('goods')->where('id', $value['good_id'])->find();
                    $list[$key]['goods_sn'] = $goods['sn'];
                    $list[$key]['goods_name'] = $goods['name'];
                    $list[$key]['goods_model'] = $goods['model'];
                    $list[$key]['store_name'] = Db::name('store')->where('id', $value['store_id'])->value('name');
                    $list[$key]['unit_name'] = Db::name('unit')->where('id', $value['unit_id'])->value('name');
                    unset($list[$key]['id']);
                }
                return $this->grid_data($list, $count, $page, $limit);
            }
        }
        return $this->fetch();
    }

    public function add()
    {
        return $this->fetch();
    }

    //编辑栏目1-1
    public function edit($id)
    {
        $info = Db::name('invpu')->where('id', $id)->find();
        $this->assign('info', $info);
        return $this->fetch();
    }
    //编辑栏目1-2
    public function save()
    {
        // 启动事务
        Db::startTrans();
        $status = 0;
        $msg = "操作失败";
        $data = $this->request->param();
        $model = new Model();
        if (empty($data['id'])) {
            $data['addtime'] = time();
            $data['enterprise_id'] = $this->EnterpriseId;
            $result = $model->allowField(true)->save($data);
            $id = $model->id;
            if ($result) {
                $status = 1;
                $msg = "添加成功";
            }
        } else {
            $id = $data['id'];
            $result = $model->allowField(true)->save($data, ["id" => $id]);
            if ($result) {
                $status = 1;
                $msg = "更新成功";
            }
        }
        //子表
        self::saveDefautl($data, $id);
        Db::commit();

        return json(['status' => $status, 'msg' => $msg]);
    }

    private function saveDefautl($data, $pid)
    {
        if (isset($data['goods_id'])) {
            $invpuGoods = [];
            foreach ($data['goods_id'] as $keys => $v) {
                $temp = [
                    'invpu_id' => $pid,
                    'goods_id' => $v,
                    'goods_mark' => $data['goods_mark'][$keys],
                    'unit_id' => $data['unit'][$keys],
                    'store_id' => $data['store_id'][$keys],
                    'number' => $data['number'][$keys],
                    'base_unit_id' => $data['base_unit_id'][$keys],
                    'base_number' => $data['base_number'][$keys],
                    'buy_price' => $data['buy_price'][$keys],
                    'total_tax_price' => $data['total_tax_price'][$keys],
                    'discount_rate' => $data['discount_rate'][$keys],
                    'discount_price' => $data['discount_price'][$keys],
                    'price' => $data['price'][$keys],
                    'tax_rate' => $data['tax_rate'][$keys],
                    'tax_price' => $data['tax_price'][$keys],
                    'sum_price_tax' => $data['sum_price_tax'][$keys],
                    'purchase_price' => $data['purchase_price'][$keys],
                    'mark' => $data['mark'][$keys],
                    'purchase_sn' => $data['purchase_sn'][$keys],
                    'enterprise_id' => $this->EnterpriseId
                ];
                array_push($invpuGoods, $temp);
            }

            $rest = Db::name('invpu_goods')->insertAll($invpuGoods);
            if (!$rest) {
                // 回滚事务
                Db::rollback();
                return json(['status' => 0, 'msg' => '添加失败']);
            }
        } else {
            // 回滚事务
            Db::rollback();
            return json(['status' => 0, 'msg' => '添加失败']);
        }
    }

    //删除栏目1-1
    public function del($id)
    {
        $status = 0;
        $msg = "操作失败";
        $del = Db::name('invpu')->where('id', $id)->update(["is_del" => 1]);
        if ($del) {
            $status = 1;
            $msg = "删除成功";
        }
        return json(['status' => $status, 'msg' => $msg]);
    }
}
